<?php
class UserinfoAction extends BaseAction{

	public $token;
	public $wecha_id;
    public $expert_model;
	public $expert_level_model;
	public $expert_title_model;
	public $userinfo_model;
	public $consultation_model;
	public $solution_model;
	public $userinfo;
	// 构造函数
    public function __construct(){
        vendor('Qrcode.qrlib');
		$agent = $_SERVER['HTTP_USER_AGENT']; 
		if(!strpos($agent,"MicroMessenger")) {
		//	echo '此功能只能在微信浏览器中使用';exit;
		}
		
        // 定义表变量，便于修改和引用
		$this->expert_model=M('Experts');
		$this->expert_level_model=M('Experts_level');
		$this->expert_title_model=M('Experts_title');
		$this->consultation_model=M('Consultation');
		$this->solution_model=M('Experts_solution');
		$this->userinfo_model = M('Userinfo');
		$this->alipay_config_db = M('Alipay_m_config');
		
		
		$this->token		= $this->_get('token');
		$this->assign('token',$this->token);
		$this->wecha_id	= $_SESSION['wecha_id'];
		
		// 根据 token 和 wecha_id 获取用户信息
		$this->userinfo = $this->userinfo_model->where(array('token'=>$this->token,'wecha_id'=>$this->wecha_id))->find();
		$this->assign('userinfo',$this->userinfo);
		
		// 获取签名认证等信息，用于页面分享的功能
		$signPackage = getSignPackage($this->token);
		
		// 获取支付宝支付 信息
		$config = $this->alipay_config_db->where(array('token' => $this->token))->find();
		// 获取微信支付信息
		$wx_config = M("wxpay_config")->where(array('token' => $this->token))->find();

		$this->assign('wxopen',$wx_config['open']);
        $this->assign('open',$config['open']);
        $this->assign('signPackage',$signPackage);
	}
	
	/**
	 * 我的咨询
	 */
	public function consultations()
	{
	    // 获取用户信息
	    $userinfo = $this->userinfo_model->where(array('token'=>$this->token,'wecha_id'=>$this->wecha_id))->find();

	    // 查询用户所有咨询
	    $consultations = $this->consultation_model->where(array('userinfo_id'=>$userinfo['id']))->order('id desc')->select();

	    // 遍历咨询
	    foreach ($consultations as $ks=>$vs)
	    {
	        // 将咨询状态 转换成字符串 ，赋予变量strStatus  咨询状态可在数据库表从consultations表字段 status 的备注中查询，也可查看方法consultationStatus()获知
	        $consultations[$ks]['strStatus'] = A('Wap/Expert')->consultationStatus($consultations[$ks]['status']);
	    }
	    $this->assign('consultations',$consultations);
	    $this->display();
	}
	
	/**
	 * 咨询详情
	 */
	public function consultationInfo()
	{
	    $consultation = $this->consultation_model->where(array('id'=>$_GET['id']))->find();
	    $status = A('Wap/Expert')->consultationStatus($consultation['status']);
	    
	    $solutions = $this->solution_model->where(array('consult_id'=>$consultation['id']))->select();
	    foreach($solutions as $ks => $vs)
	    {
	        $expert = $this->expert_model->where(array('expert_id'=>$solutions[$ks]['expert_id']))->find();
	        $expert_level  = $this->expert_level_model->where(array('expert_id'=>$expert['expert_id']))->find();
	        $expert_title  = $this->expert_title_model->where(array('title_id'=>$expert['title_id']))->find();
	        $solutions[$ks]['expert_name'] = $expert['expert_name'];
	        $solutions[$ks]['keywords'] = $expert['keywords'];
	        $solutions[$ks]['expert_level'] = $expert_level['name'];
	        $solutions[$ks]['expert_title'] = $expert_title['name'];
	        if ($solutions[$ks]['is_best'] == 1)
	        {
	            $this->assign('is_check',1);
	        }
	    }
	    $this->assign('status',$status);
	    $this->assign('consultation',$consultation);
	    $this->assign('solutions',$solutions);
	    
	   if($_POST) 
	   {
	       error_log("******************UserinfoAction consultationInfo() _POST solution_id = ".$_POST['solution_id'],0);
	       $solution_id = $_POST['solution_id']; 
	       $solution = $this->solution_model->where(array('id'=>$solution_id))->find();
	       $this->solution_model->where(array('id'=>$solution_id))->save(array('is_best'=>1));
	       $expert = $this->expert_model->where(array('expert_id'=>$solution['expert_id']))->find();
	       if ($expert && $consultation['consult_type'] == 2)
	       {
	           $pay_fee = floatval($consultation['consult_fee'] * 0.5);
	           $this->expert_model->where(array('expert_id'=>$expert['expert_id']))->setInc('satisfaction',1);
	           M('Consult_payment')->where(array('consult_id'=>$consultation['id'],'expert_id'=>$expert['expert_id']))->save(array('pay_fee'=>$pay_fee));
	           

	           $other_fee = floatval($consultation['consult_fee'] * 0.25);
	           $experts_solutions = M('Experts_solution')->where(array('consult_id'=>$consultation['id']))->select();
	           foreach ($experts_solutions as $ks=>$vs)
	           {
	               M('Consult_payment')->where(array('consult_id'=>$consultation['id'],'expert_id'=>$experts_solutions[$ks]['expert_id']))->save(array('pay_fee'=>$other_fee));
	           }
	       
	       }
	       
	       error_log("******************UserinfoAction consultationInfo() _POST submit = ".$_POST["submit2"],0);
	       if($_POST["submit2"]=='submit2')
	       {
	          $this->consultation_model->where(array('id'=>$solution['consult_id']))->save(array('status'=>8));// 咨询结束(已解答)
	          if($consultation['consult_type'] != 1)
	          {
	              foreach ($experts_solutions as $ks=>$vs)
	              {
	                  if($experts_solutions[$ks]['solution_time'] <= 0)
	                  {
	                      $this->consultation_model->where(array('id'=>$solution['consult_id']))->save(array('status'=>10));// 咨询结束(提前)
	                  }
	              }
	             
	          }
	          
	          $this->redirect(U('Userinfo/consultations',array('token'=>$this->token)));
	       }
	       else
	       {
	           $this->redirect(U('Userinfo/addToConsult',array('token'=>$this->token,'id'=>$consultation['id'])));
	       }
	       
	   }
	   else
	   {
	       $this->display();
	   }
	}
	
	/**
	 * 取消咨询
	 */
	public function cancelConsult()
	{
	    $consultation = $this->consultation_model->where(array('id'=>$_GET['id']))->find();
	    if($consultation)
	    {
	        $this->consultation_model->where(array('id'=>$_GET['id']))->save(array('status'=>7));// 将咨询状态修改为咨询结束（取消）
	        $this->redirect(U('Userinfo/consultations',array('token'=>$this->token)));
	    }
	    
	}
	
	/**
	 * 申请退款
	 */
	public function requestRefund()
	{
	    $consultation = $this->consultation_model->where(array('id'=>$_GET['id']))->find();
	    if($consultation)
	    {
	        $this->consultation_model->where(array('id'=>$_GET['id']))->save(array('status'=>11));// 将咨询状态修改为退款
	        $this->redirect(U('Userinfo/consultations',array('token'=>$this->token)));
	    }
	}
	
	/**
	 * 追加咨询
	 */
	public function addToConsult()
	{
	    error_log("******************UserinfoAction addToConsut() id = ".$_GET['id'],0);
	    $consultation = $this->consultation_model->where(array('id'=>$_GET['id']))->find();
	    $solution = $this->solution_model->where(array('consult_id'=>$consultation['id'],'is_best'=>1))->find();
	    $consultation['status'] = A('Wap/Expert')->consultationStatus($consultation['status']);
	    $expert = $this->expert_model->where(array('expert_id'=>$solution['expert_id']))->find();
	    $expert_level  = $this->expert_level_model->where(array('expert_id'=>$expert['expert_id']))->find();
	    $expert_title  = $this->expert_title_model->where(array('title_id'=>$expert['title_id']))->find();
	    $this->assign('expert',$expert);
	    $this->assign('expert_level',$expert_level['name']);
	    $this->assign('expert_title',$expert_level['name']);
	    $this->assign('consultation',$consultation);
	    $this->assign('solution',$solution);
	    if($_POST)
	    {
	        $data['addto_desc'] = $_POST['addto_desc'];
	        $data['addto_time'] = time();
	        $data['status'] = 6;// 咨询状态修改为 咨询追问
	        $this->consultation_model->where(array('id'=>$_GET['id']))->save($data);
	        $this->solution_model->where(array('consult_id'=>$consultation['id'],'is_best'=>1))->save(array('status'=>3)); // 咨询有追问
	        $this->display('addToConsultConfirm');
	    }
	    else 
	    {
	        $this->display();
	    }
	   
	}
	/**
	 * 我的解答
	 */
	public function solutions()
	{
	    $expert = $this->expert_model->where(array('userinfo_id'=>$this->userinfo['id']))->find();
	    $solutions = $this->solution_model->where(array('expert_id'=>$expert['expert_id']))->order('id desc')->select();
	    foreach ($solutions as $ks=>$vs)
	    {
	        $consulation = $this->consultation_model->where(array('id'=>$solutions[$ks]['consult_id']))->find();
	        $solutions[$ks]['consult_desc'] = $consulation['consult_desc'];
	        $solutions[$ks]['consult_time'] = $consulation['consult_time'];
	        $solutions[$ks]['consult_fee'] = $consulation['consult_fee'];
	        $solutions[$ks]['solution_status'] = $this->solutionStatus($solutions[$ks]['status']);
	        if($consulation['status'] > 10) //  咨询申请退款的情况下 
	        {
	            $solutions[$ks]['refund'] = 1;
	        }
	         
	    }
	    $this->assign('solutions',$solutions);
	    $this->display();
	}
	
	/**
	 * 我的解答详情
	 */
	public function solutionInfo()
	{
	    $is_add = 0;
	    $is_addsolution = 0;
	    $solution = $this->solution_model->where(array('id'=>$_GET['id']))->find();
	    $consultation = $this->consultation_model->where(array('id'=>$solution['consult_id']))->find();
	    if($consultation['addto_time'])
	    {
	        $is_add = 1;
	        if($solution['addsolution_time'])
	        {
	            $is_addsolution = 1;
	        }
	    }
	    
	    $solution_status = $this->solutionStatus($solution['status']);
	     
	    $this->assign('is_add',$is_add);
	    $this->assign('is_addsolution',$is_addsolution);
	    $this->assign('solution_status',$solution_status);
	    $this->assign('solution',$solution);
	    $this->assign('consultation',$consultation);
	    if ($_POST)
	    {
	        $data['addsolution_desc'] = $_POST['addsolution_desc'];
	        $data['addsolution_time'] = time();
	        if($this->solution_model->where(array('id'=>$_GET['id']))->save($data))
	        {
	            $this->consultation_model->where(array('id'=>$solution['consult_id']))->save(array('status'=>8));// 将咨询状态改为 咨询结束(已解答)
	        }
	        
	        $this->redirect(U('Userinfo/solutions',array('token'=>$this->token)));
	    }
	    
	    $this->display();
	}
	
	/**
	 * 抢答页面
	 */
	public function toSolution()
	{
	    $this->solution_model->where(array('id'=>$_GET['id']))->save(array('status'=>1)); // 解答状态 改为已抢答
	    $solution = $this->solution_model->where(array('id'=>$_GET['id']))->find();
	    $this->consultation_model->where(array('id'=>$solution['consult_id']))->save(array('status'=>4));// 咨询状态改为 已抢答
	    $this->assign('solution',$solution);
	    if ($_POST)
	    {
	        import('ORG.UploadFile');
	        $upload = new UploadFile();// 实例化上传类
	        $upload->maxSize  = -1;// 设置附件上传大小
	        $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
	        $firstLetter=substr($this->token,0,1);
	        $upload->savePath =  './uploads/'.$firstLetter.'/'.$this->token.'/';// 设置附件上传目录
	        if($_FILES['solution_img']['name'])
	        {
	            if(!$upload->upload()) {// 上传错误提示错误信息
	                $this->error($upload->getErrorMsg());
	            }else{// 上传成功 获取上传文件信息
	                $info =  $upload->getUploadFileInfo();
	                $solution_img = $info[0]['savepath'].$info[0]['savename'];
	            }
	        }
	        $data['solution_desc'] = $_POST['solution_desc'];
	        $data['solution_time'] = time();
	        $data['solution_img'] = $solution_img;
	        $data['status'] = 2;// 咨询状态改为 解答中
	        $this->solution_model->where(array('id'=>$_GET['id']))->save($data);
	        $solution = $this->solution_model->where(array('id'=>$_GET['id']))->find();
	        $consultation = $this->consultation_model->where(array('id'=>$solution['consult_id']))->save(array('status'=>5));// 咨询状态改为 解答中
	        $this->assign('solution',$solution);
	        $this->display('confirmSolution');
	    }
	    else 
	    {
	        $this->display();
	    }
	}
	
	/**
	 * 提交解答
	 */
	public function confirmSolution()
	{
	    $solution = $this->solution_model->where(array('id'=>$_GET['id']))->find();
	    $this->assign('solution',$solution);
	    $this->display();
	}
	
	
	/**
	 * 我要认证为专家
	 */
	public  function  authExpert()
	{
	    $checkdata = $this->expert_model->where(array('userinfo_id'=>$this->userinfo['id']))->find();
	    if($checkdata)
	    {
	        $this->redirect(U('Userinfo/setExpert',array('token'=>$this->token)));
	    }
	    if(IS_POST)
	    {
	        $this->all_insert('Experts');
	        import('ORG.UploadFile');
	        $upload = new UploadFile();// 实例化上传类
	        $upload->maxSize  = -1;// 设置附件上传大小
	        $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
	        $firstLetter=substr($this->token,0,1);
	        $upload->savePath =  './uploads/'.$firstLetter.'/'.$this->token.'/';// 设置附件上传目录
	        if($_FILES['head_img']['name'])
	        {
	            if(!$upload->upload()) {// 上传错误提示错误信息
	                $this->error($upload->getErrorMsg());
	            }else{// 上传成功 获取上传文件信息
	                $info =  $upload->getUploadFileInfo();
	                $head_img = $info[0]['savepath'].$info[0]['savename'];
	            }
	        }
	        
	        $expert = $this->expert_model->where(array('userinfo_id'=>$this->userinfo['id']))->find();
	        $this->expert_model->where(array('expert_id'=>$expert['expert_id']))->save(array('head_img'=>$head_img));
	        $this->redirect(U('Userinfo/authVideo',array('token'=>$this->token)));
	       //$this->success('添加成功',U('Userinfo/userinfo',array('token'=>$this->token)));
	      //  $this->all_insert('Experts','/userinfo?token='.$this->token);
	    }
	    else
	    {
	        //专家级别分类
	        $levelWhere=array('token'=>$this->token);
	        $levels=$this->expert_level_model->where($levelWhere)->select();
	        $this->assign('levels',$levels);
	         
	        //专家职称
	        $titleWhere=array('token'=>$this->token);
	        $titles=$this->expert_title_model->where($titleWhere)->select();
	        $this->assign('titles',$titles);
	         
	        $levelsOptions=$this->levelsOptions($levels,0);
	        $this->assign('levelsOptions',$levelsOptions);
	        
	        $titlesOptions=$this->titlesOptions($titles,0);
	        $this->assign('titlesOptions',$titlesOptions);
	        $this->display('setExpert');
	    }
	}
	
	/**
	 * 认证专家 最后一步
	 */
	public function authVideo()
	{
	    $this->display();
	}
	
	/**
	 * 专家认证信息
	 */
	public function setExpert()
	{
	    $checkdata = $this->expert_model->where(array('userinfo_id'=>$this->userinfo['id']))->find();
	    if(IS_POST){
	        $where=array('expert_id'=> $checkdata['expert_id']);
	        $check=$this->expert_model->where($where)->find();
	        if($check==false)$this->error('非法操作');
	        if($this->expert_model->create()){
	            if($this->expert_model->where($where)->save($_POST)){
	                $this->success('修改成功',U('Userinfo/userinfo',array('token'=>$this->token)));
	            }else{
	                $this->error('操作失败');
	            }
	        }else{
	            $this->error($this->expert_model->getError());
	        }
	    }else{
	        //专家级别分类
	        $levelWhere=array('token'=>$this->token);
	        $levels=$this->expert_level_model->where($levelWhere)->select();
	        $this->assign('levels',$levels);
	        	
	        $thisLevel=$this->expert_level_model->where(array('level_id'=>$checkdata['level_id']))->find();
	        $this->assign('thisLevel',$thisLevel);
	        	
	        //专家职称
	        $titleWhere=array('token'=>$this->token);
	        $titles=$this->expert_title_model->where($titleWhere)->select();
	        $this->assign('titles',$titles);
	    
	        $thisTitle=$this->expert_title_model->where(array('title_id'=>$checkdata['title_id']))->find();
	        $this->assign('thisTitle',$thisTitle);
	        	
	        $levelsOptions=$this->levelsOptions($levels,$checkdata['level_id']);
	        $this->assign('levelsOptions',$levelsOptions);
	        	
	        $titlesOptions=$this->titlesOptions($titles,$checkdata['title_id']);
	        $this->assign('titlesOptions',$titlesOptions);
	        //
	        $this->assign('expert',$checkdata);
	        $this->display();
	   }
	}
	
	/**
	 * 科研院所认证
	 */
	public function authResearchInstitutes()
	{
	    $this->display();
	}
	
	/**
	 * 我的关注
	 */
	public function collect()
	{
		if(!$_SESSION['wecha_id']){
			      getCode("index",$this->token);
				  return;
	    }
		$data['wecha_id']=$this->wecha_id;
		$data['token']=$this->token;
		$userinfo = $this->userinfo_model->where($data)->find(); 
		$user_id['user_id']  = $userinfo['id'];
		
		$user_id['is_collect']  = 1;
		$count = M("collect_experts")->where($user_id)->count();
		$collects = M("collect_experts")->where($user_id)->field('expert_id')->select(); 
		$expert_ids = A('Userinfo')->db_in($collects);
		$wheregids['expert_id'] = array('in',$expert_ids);
		$collect_experts=$this->expert_model->where($wheregids)->select();
		$this->assign('token',$this->_get('token')); 
		$this->assign('count',$count);
		$this->assign('userinfo',$userinfo);
		$this->assign('collects',$collect_experts);
		$this->assign('staticFilePath',str_replace('./','/',THEME_PATH.'common/css/product'));
		$this->display();	
	}
	
/**
     * 关注专家
     */
    public function collectExpert()
    {
        error_log("***************UserinfoAction collectExpert() come in*********************",0);
        $data["wecha_id"] = $this->wecha_id;
        $data['token']=$this->token;
        $userinfo = $this->userinfo_model->where($data)->find();
        error_log("***************UserinfoAction collectExpert() userinfo*********************".print_r($userinfo,1),0);
        $where["user_id"] = $userinfo['id'];
        $where["expert_id"] =  $_GET['expert_id'];
        $user_collect = M("collect_experts")->where($where)->find();
        if($user_collect)
        {
            //已经存在关注记
            // 如果当前为关注，则取消关注
            if($user_collect['is_collect'] == 1)
            {
                $data['is_collect'] = 0;
            }
            else
            {
                $data["is_collect"] = 1;
            }
            M("collect_experts")->where($where)->save($data);
        }
        else
        {
            error_log("***************UserinfoAction collectExpert() add*********************",0);
            $data["user_id"] = $userinfo['id'];
            $data["expert_id"] =  $_GET['expert_id'];
            $data["add_time"] = time();
            $data["is_collect"] = 1;
            error_log("***************UserinfoAction collectExpert() data*********************".print_r($data,1),0);
            M("collect_experts")->add($data);
            error_log("***************UserinfoAction collectExpert() add*********************".M("collect_experts")->getLastSql(),0);
        }
        $this->ajaxReturn($data["is_collect"]);
    }
	
    /**
     * 取消关注专家
     */
	public function deleteCollect(){
        $expert_id=$_GET['expert_id'];
        $result=M('userinfo')->where(array('wecha_id'=>$this->wecha_id,'token'=>$this->token))->find();       
        M('collect_experts')->where(array('user_id'=>$result['id'],'expert_id'=>$expert_id))->delete();               
		$this->redirect(U('Userinfo/collect',array('token'=>$_GET['token'])));
	}
	
	/**
	 * 个人中心
	 */
	public function userinfo()
	{
		error_log("add by hutingting UserinfoAction userinfo wecha_id*********************************************".$_SESSION['wecha_id'],0);	
		if(!$_SESSION['wecha_id']){
			      getCode("userinfo",$this->token);
	    }
		else
		{
			$jsondecode = $_SESSION['jsondecode'];
			error_log("add by hutingting UserinfoAction jsondecode ***********************".json_decode($jsondecode),0);
			$userinfo = M("userinfo")->where(array('token'=>$this->token,'wecha_id'=>$this->wecha_id))->find();
			if($userinfo)
			{
				error_log("add by hutingting UserinfoAction userinfo ***********************".print_r($userinfo,1),0);
				$this->assign('nickname',$userinfo['wechaname']);
				$this->assign('headimgurl',$jsondecode->{"headimgurl"});
			}
		
		$this->assign('userinfo',$userinfo);
		$this->assign('staticFilePath',str_replace('./','/',THEME_PATH.'common/css/product'));
        $this->display();
		}
        
	}

	function db_in($types_ids)
	{
		 $ids = '';
		 if(empty($types_ids))
		 {
			  return '';
		 }
		 else
		 {
			 foreach($types_ids as $k=>$val)
			{
			 if( is_array($val) ) 
			 {
				 foreach( $val as $value) 
				 {
					 if ($value !== '')
            		{
               	 	  $ids .= $ids ? ",$value" : "$value";
            		}
					// $ids .=  $value.',';   
				 }
				  
			 }
			 else 
			 {
				 $ids .= $k.'=>'.$val.','; 
			 }

			} //意思是for $book each $value( as )    
  
		 }
		 return $ids;
	}
	
	//专家级别下拉列表
	public function levelsOptions($levels,$selectedid){
	    $str='';
	    if ($levels){
	        foreach ($levels as $l){
	            $selected='';
	            if ($l['level_id']==$selectedid){
	                $selected=' selected';
	            }
	            $str.='<option value="'.$l['level_id'].'"'.$selected.'>'.$l['name'].'</option>';
	        }
	    }
	    return $str;
	}
	
	//商品类别下拉列表
	public function titlesOptions($titles,$selectedid){
	    $str='';
	    if ($titles){
	        foreach ($titles as $t){
	            $selected='';
	            if ($t['title_id']==$selectedid){
	                $selected=' selected';
	            }
	            $str.='<option value="'.$t['title_id'].'"'.$selected.'>'.$t['name'].'</option>';
	        }
	    }
	    return $str;
	}
	
	public function solutionStatus($st)
	{
	    if ($st == 1)
	    {
	        $status = '已抢答';
	    }
	    elseif ($st == 2)
	    {
	        $status = '咨询已解答';
	    }
	    elseif ($st == 3)
	    {
	        $status = '咨询有追问';
	    }
	    else
	    {
	        $status = '新咨询';
	    }
	    
	    return $status;
	}
	
} // end class UserinfoAction

?>